package com.slorgs.business.utils

import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import com.slorgs.business.common.Constant
import com.slorgs.infrastructure.model.User
import org.slf4j.LoggerFactory

class TokenUtil {

    companion object {
        private val log = LoggerFactory.getLogger(TokenUtil::class.java)

        /**
         * 加密token.
         */
        fun getToken(user: User): String? {
            return JWT
                .create()
                .withClaim("loginName", user.loginName)
                .withClaim("realName", user.realName)
                .withClaim("role", user.role)
                .withClaim("timeStamp", System.currentTimeMillis())
                .sign(Algorithm.HMAC256(Constant.TOKEN_KEY))
        }

        fun parseToken(token: String?): Map<String, String> {
            val map = HashMap<String, String>()
            val decodedjwt = JWT.require(Algorithm.HMAC256(Constant.TOKEN_KEY))
                .build().verify(token)
            val loginName = decodedjwt.getClaim("loginName")
            val role = decodedjwt.getClaim("role")
            val realName = decodedjwt.getClaim("realName")
            val timeStamp = decodedjwt.getClaim("timeStamp")
            map["realName"] = realName.asString()
            map["loginName"] = loginName.asString()
            map["role"] = role.asString()
            map["timeStamp"] = timeStamp.asLong().toString()
            return map
        }
    }
}